document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const orderId = urlParams.get('orderId');
    const action = urlParams.get('action');

    if (!orderId) {
        window.location.href = 'admin-orders.html';
        return;
    }

    // 加载订单详情
    loadOrderDetail(orderId);

    // 如果是发货操作，显示发货表单
    if (action === 'ship') {
        document.getElementById('shippingForm').style.display = 'block';
        document.getElementById('shippingDetail').style.display = 'none';

        // 初始化物流公司下拉框
        const shippingCompanies = [
            {code: 'SF', name: '顺丰速运'},
            {code: 'STO', name: '申通快递'},
            {code: 'YTO', name: '圆通速递'},
            {code: 'ZTO', name: '中通快递'},
            {code: 'YD', name: '韵达快递'},
            {code: 'EMS', name: '邮政EMS'},
            {code: 'JD', name: '京东物流'}
        ];

        const companySelect = document.getElementById('shippingCompanyInput');
        const shippingNoInput = document.getElementById('shippingNoInput');

        // 添加默认选项
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请选择物流公司';
        companySelect.appendChild(defaultOption);

        // 添加物流公司选项
        shippingCompanies.forEach(company => {
            const option = document.createElement('option');
            option.value = company.code;
            option.textContent = company.name;
            companySelect.appendChild(option);
        });

        // 监听物流公司选择变化
        companySelect.addEventListener('change', function() {
            if (this.value) {
                // 根据选择的物流公司生成单号
                shippingNoInput.value = generateTrackingNumber(this.value);
            } else {
                shippingNoInput.value = '';
            }
        });
    }

    // 绑定发货按钮事件
    const submitShippingBtn = document.getElementById('submitShipping');
    if (submitShippingBtn) {
        submitShippingBtn.addEventListener('click', function() {
            const company = document.getElementById('shippingCompanyInput').value;
            const no = document.getElementById('shippingNoInput').value;

            if (!company || !no) {
                alert('请填写完整的物流信息');
                return;
            }

            shipOrder(orderId, company, no);
        });
    }

    // 绑定取消订单按钮事件
    const cancelOrderBtn = document.getElementById('cancelOrderBtn');
    if (cancelOrderBtn) {
        cancelOrderBtn.addEventListener('click', function() {
            if (confirm('确定要取消此订单吗？')) {
                cancelOrder(orderId);
            }
        });
    }

    // 绑定标记完成按钮事件
    const completeOrderBtn = document.getElementById('completeOrderBtn');
    if (completeOrderBtn) {
        completeOrderBtn.addEventListener('click', function() {
            if (confirm('确定要标记此订单为已完成吗？')) {
                completeOrder(orderId);
            }
        });
    }
});

// 加载订单详情
function loadOrderDetail(orderId) {
    fetch(`http://localhost:8080/api/admin/orders/${orderId}`)
        .then(response => response.json())
        .then(order => {
            if (!order) {
                window.location.href = 'admin-orders.html';
                return;
            }

            // 填充订单基本信息
            document.getElementById('orderNo').textContent = order.orderNo || '--';
            document.getElementById('userId').textContent = order.userId || '--';

            // 处理订单状态
            let statusText = '';
            switch(order.status) {
                case 0: statusText = '待支付'; break;
                case 1: statusText = '已支付'; break;
                case 2: statusText = '已发货'; break;
                case 3: statusText = '已完成'; break;
                case 4: statusText = '已取消'; break;
                default: statusText = '未知状态';
            }
            document.getElementById('orderStatus').textContent = statusText;

            // 处理时间信息
            document.getElementById('createTime').textContent =
                order.paymentTime ? new Date(order.paymentTime).toLocaleString() : '--';
            document.getElementById('paymentTime').textContent =
                order.paymentTime ? new Date(order.paymentTime).toLocaleString() : '--';
            document.getElementById('shippingTime').textContent =
                order.shippingTime ? new Date(order.shippingTime).toLocaleString() : '--';
            document.getElementById('completeTime').textContent =
                order.completeTime ? new Date(order.completeTime).toLocaleString() : '--';

            // 处理金额信息
            document.getElementById('totalAmount').textContent =
                '¥' + (order.totalAmount || 0).toFixed(2);
            document.getElementById('freightAmount').textContent =
                '¥' + (order.freightAmount || 0).toFixed(2);
            document.getElementById('paymentAmount').textContent =
                '¥' + (order.paymentAmount || 0).toFixed(2);

            // 处理订单备注
            document.getElementById('note').textContent = order.note || '--';

            // 处理收货信息
            const address = order.address || {};
            document.getElementById('receiverName').textContent = address.name || '--';
            document.getElementById('receiverPhone').textContent = address.phone || '--';
            document.getElementById('receiverAddress').textContent =
                [address.province, address.city, address.district, address.addr]
                    .filter(Boolean).join(' ') || '--';

            // 处理物流信息
            if (order.shippingCompany && order.shippingNo) {
                document.getElementById('shippingCompany').textContent = order.shippingCompany || '--';
                document.getElementById('shippingNo').textContent = order.shippingNo || '--';
            } else {
                document.getElementById('shippingDetail').style.display = 'none';
            }

            // 填充商品列表
            const itemListEl = document.getElementById('itemList');
            itemListEl.innerHTML = '';

            (order.orderItems || []).forEach(item => {
                const row = document.createElement('tr');
                const imageUrl = formatImagePath(item.productImage);
                row.innerHTML = `
        <td>
             <div class="order-item">
                                    <img src="${imageUrl}" alt="${item.productName}" 
                                         onerror="this.src='/static/no-image.png'">
                                    <div>
                                        <p>${item.productName}</p>
            </div>
        </td>
        <td>¥${(item.productPrice || 0).toFixed(2)}</td>
        <td>${item.quantity || '0'}</td>
        <td>¥${(item.totalPrice || 0).toFixed(2)}</td>
    `;
                itemListEl.appendChild(row);
            });

            // 根据订单状态显示/隐藏操作按钮
            if (order.status === 4) { // 已取消
                document.getElementById('cancelOrderBtn').style.display = 'none';
                document.getElementById('completeOrderBtn').style.display = 'none';
            } else if (order.status === 3) { // 已完成
                document.getElementById('cancelOrderBtn').style.display = 'none';
                document.getElementById('completeOrderBtn').style.display = 'none';
            } else if (order.status === 2) { // 已发货
                document.getElementById('cancelOrderBtn').style.display = 'none';
                document.getElementById('completeOrderBtn').style.display = 'block';
            } else if (order.status === 1) { // 已支付
                document.getElementById('cancelOrderBtn').style.display = 'block';
                document.getElementById('completeOrderBtn').style.display = 'none';
            } else { // 待支付
                document.getElementById('cancelOrderBtn').style.display = 'block';
                document.getElementById('completeOrderBtn').style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Error loading order detail:', error);
            alert('加载订单详情失败，请稍后重试');
            window.location.href = 'admin-orders.html';
        });
}

// 发货操作
function shipOrder(orderId, company, no) {
    fetch(`http://localhost:8080/api/admin/orders/${orderId}/ship`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `shippingCompany=${encodeURIComponent(company)}&shippingNo=${encodeURIComponent(no)}`
    })
        .then(response => {
            if (response.ok) {
                alert('发货成功！');
                window.location.href = `admin-order-detail.html?orderId=${orderId}`;
            } else {
                alert('发货失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
}

// 取消订单
function cancelOrder(orderId) {
    fetch(`http://localhost:8080/api/admin/orders/${orderId}/cancel`, {
        method: 'PUT'
    })
        .then(response => {
            if (response.ok) {
                alert('订单已取消');
                window.location.reload();
            } else {
                alert('取消订单失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
}

// 标记订单完成
function completeOrder(orderId) {
    fetch(`http://localhost:8080/api/admin/orders/${orderId}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'status=3'
    })
        .then(response => {
            if (response.ok) {
                alert('订单已标记为完成');
                window.location.reload();
            } else {
                alert('操作失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
}

// 格式化图片路径
function formatImagePath(imagePath) {
    if (!imagePath) return '/static/no-image.png';
    if (imagePath.startsWith('http')) return imagePath;

    const cleanPath = imagePath
        .replace(/^\.\//, '')
        .replace(/^\/?upload\//, '')
        .replace(/^\/?static\//, '');

    return `/static/upload/${cleanPath}`;
}
// 生成物流单号函数
function generateTrackingNumber(companyCode) {
    const date = new Date();
    const datePart = date.getFullYear().toString().substr(-2) +
        (date.getMonth() + 1).toString().padStart(2, '0') +
        date.getDate().toString().padStart(2, '0');
    const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');

    // 使用物流公司代码作为前缀
    return `${companyCode}${datePart}${randomPart}`;
}
